﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MT4Trainer
{
    public class NQuantMath
    {
        /// <summary>
        ///  Calculates the variance over a double array.
        /// </summary>
        /// <param name="input"> The input. </param>
        /// <returns>
        ///  The calculated variance.
        /// </returns>
        public static double CalculateVariance(double[] input)
        {
            double sumOfSquares = 0.0;
            double total = 0.0;
            foreach (double d in input)
            {
                total += d;
                sumOfSquares += Math.Pow(d, 2);
            }
            int n = input.Length;
            return ((n * sumOfSquares) - Math.Pow(total, 2)) / (n * (n - 1));
        }


        /// <summary>
        ///  Calculates the variance over a double array.
        /// </summary>
        /// <param name="input"> The input. </param>
        /// <returns>
        ///  The calculated variance.
        /// </returns>
        public static double CalculateVarianceParallel(double[] input)
        {
            double sumOfSquares = 0.0;
            double total = 0.0;
            Parallel.ForEach(input, d =>
            {
                total += d;
                sumOfSquares += Math.Pow(d, 2);
            });
            int n = input.Length;
            return ((n * sumOfSquares) - Math.Pow(total, 2)) / (n * (n - 1));
        }
    }
}
